<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller;

use buwang\base\AdminBaseController;
use think\facade\View;
use app\manage\model\ConfigTab;
use app\manage\model\Config as ConfigModel;
use app\manage\model\Member;
use app\manage\model\AuthNode;
use buwang\util\Util;
use app\common\model\Miniapp;

class Config extends AdminBaseController
{
    /*protected $middleware = [
        'login' => ['except' => []]
    ];*/
    protected $saveDataUid = 0;


    public function index()
    {
        $miniapp = Miniapp::select()->toArray();
        //var_dump($_COOKIE['token']);die;
        //View::assign('url', 'index页面');
        return view('',[ 'miniapp' => $miniapp]);
    }


    /**
     * 配置分类列表
     *
     * @return \think\Response
     */
    public function getlist()
    {

        //var_dump($uid);die;
        //搜索条件
        $map = array();
        $sort = 'a.sort desc,a.id desc';
        //页数
        $page = input('page/d');
        //条数
        $limit = input('limit/d');
//        //时间开始
//        $time_start    = input('beginTime/s');
//        //时间结束
//        $time_end    = input('endTime/s');
        //订单状态
        $type = input('type/s');
        //订单号
        $title = input('title/s');
        //直播分类
        $is_show = input('is_show/s');
        $scopes = input('scopes/s');
        $dir = input('dir/s');//应用

        //手机号
        $tab_name = input('tab_name/s');

        //订单状态
        if ($type != null) {
            $map[] = ['a.type', '=', $type];
        }
        if ($is_show !== '') {
            $map[] = ['a.is_show', '=', $is_show];
        }
        if ($scopes !== '') {
            $map[] = ['a.scopes', '=', $scopes];
        }
        if ($tab_name) {
            $map[] = ['a.tab_name', 'like', $tab_name . '%'];
        }

        if ($title) {
            $map[] = ['a.title', 'like', $title . '%'];
        }
        if ($dir) {
            $map[] = ['a.dir', '=', $dir];
        }


//        //时间区间
//        if($time_start!=null){
//            $time_start = strtotime($time_start);
//            $map[] = ['a.add_time','>=',$time_start];
//            if($time_end!=null){
//                $time_end = strtotime($time_end);
//                $map[] = ['a.add_time','<=',$time_end];
//            }
//        }elseif($time_end!=null){
//            $time_end = strtotime($time_end);
//            $map[] = ['a.add_time','<=',$time_end];
//            if($time_start!=null){
//                $time_start = strtotime($time_start);
//                $map[] = ['a.add_time','>=',$time_start];
//            }
//        }

        // $map[] = ['a.is_del','=', 0];

        //门店列表
        $list = ConfigTab::alias('a')
            ->field(['a.*','m.title as miniapp_name'])
            ->join('miniapp m','m.dir = a.dir','left')
            ->where($map)
            ->page($page, $limit)
            ->order($sort)
            ->select();
        $count = ConfigTab::alias('a')
            ->join('miniapp m','m.dir = a.dir','left')
            ->where($map)
            ->count();

        //总数
        //列表数据
        $data = array();
        $data['code'] = 0;
        $data['msg'] = '查询成功';
        $data['count'] = $count;
        $data['data'] = $list;
        return json($data);
    }

    /**
     * 删除/批量删除
     *
     * @return \think\Response
     */
    public function softdleting()
    {
        //门店ids
        $ids = input('ids/s');
        $ids_array = explode(',', $ids);
        $list = array();
        foreach ($ids_array as $key) {
            //如果存在子配置则不允许删除
            if (ConfigTab::haveConfig($key)) {
                return 'paramFail';
            }


            ConfigTab::destroy($key);
        }

        //Offline::destroy($ids_array);
        return 'success';
    }


    public function edit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //判断是否存在唯一标识

            //TODO: 应用配置  变更判断为租户数据与应用（dir）数据与系统数据之间不允许重复，不同应用（dir）之间允许字段重复 20201118
            $param['dir'] = $param['dir'] ?? '';//不存在为空串
            $count = ConfigTab::where('tab_name', $param['tab_name'])->where('dir', $param['dir'])->where('id', '<>', $param['id'])->count();
            if ($count) return $this->error('该字段已存在');
            $count = ConfigModel::where('config_name', $param['tab_name'])->count();
            if ($count) return $this->error('该字段配置中已存在');

            $result = ConfigTab::update($param);
            if ($result) {
                //xn_add_admin_log('修改管理组名称');
                return $this->success('更新成功');
            } else {
                return $this->error('操作失败');
            }
        }
        $id = $this->request->get('id');
        $data = ConfigTab::find($id);
        $miniapp = Miniapp::select()->toArray();
        return view('', ['entity' => $data, 'miniapp' => $miniapp]);
    }


    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            // if(!$param['auth_name']) return $this->error('权限标识必填');
            //判断是否存在唯一标识
            //TODO: 应用配置  变更判断为租户数据与应用（dir）数据与系统数据之间不允许重复，不同应用（dir）之间允许字段重复 20201118
            $param['dir'] = $param['dir'] ?? '';//不存在为空串
            $count = ConfigTab::where('tab_name', $param['tab_name'])->where('dir', $param['dir'])->count();
            if ($count) return $this->error('该字段已存在');
            $count = ConfigModel::where('config_name', $param['tab_name'])->count();
            if ($count) return $this->error('该字段配置中已存在');
            $result = ConfigTab::create($param);
            if ($result) {
                return $this->success('操作成功');
            } else {
                return $this->error('操作失败');
            }
        }
        $miniapp = Miniapp::select()->toArray();

        return view('edit', ['entity' => null, 'miniapp' => $miniapp]);
    }


    /**
     * 更改开启状态
     *
     * @return \think\Response
     */
    public function setshow()
    {
        //门店id
        $id = input('id/d');
        $sort = input('sort/s', null);
        $data = ConfigTab::find($id);
        if ($sort === null) {
            //门店开启状态
            //$status = input('status/s');
            //var_dump($open);die;//常用函数
            //$data->status     = !$status;
            // if($status==='1') $data->status  = '0';
            if ($data['is_show'] === 0) {
                $data->is_show = 1;
            } elseif ($data['is_show'] === 1) {
                $data->is_show = 0;
            };
        } else {
            $data['sort'] = $sort;
        }
        $data->save();

        return 'success';
    }

    public function addconfig()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            // if(!$param['auth_name']) return $this->error('权限标识必填');
            //var_dump($param['value']);die;
            //得到配置分类的scope
            if (!isset($param['tab_id']) || !$param['tab_id']) return $this->error('分类不存在');
            $ConfigTab = ConfigTab::find($param['tab_id']);
            if (!$ConfigTab) return $this->error('配置分类不存在');
            //判断是否存在唯一标识
            $count = ConfigModel::where('config_name', $param['config_name'])->where('dir',$ConfigTab['dir'])->count();
            if ($count) return $this->error('该字段已存在');
            $count = ConfigTab::where('tab_name', $param['config_name'])->count();
            if ($count) return $this->error('该字段分类中已存在');
            $param['scopes'] = $ConfigTab['scopes'];
            $param['dir'] = $ConfigTab['dir'];
            unset($param['id']);
            //配置提示如果为空则使用默认配置
            if (!isset($param['desc']) || !$param['desc']) $param['desc'] = $param['info'];
            //转移富文本
            if ($param['type'] == 'r_textarea') $param['value'] = Util::r_text_decode($param['value']);
            //插入分类标识
            $param['tab_name'] = $ConfigTab['tab_name'];
            $res = $res1 = $res2 = true;
            ConfigModel::beginTrans();
            try {
                //2:如果是租户配置，需给所有顶级租户添加数据
                if ($param['scopes'] == 'member') {
                    //查询所有租户
                    $members = Member::where('parent_id', 0)->select()->toArray();
                    $configData = array();
                    //添加原始数据
                    $entity = $param;
                    $entity['member_id'] = 0;
                    $configData[] = $entity;
                    /**2020 07 22 配置懒加载注释掉批量添加**/
                    //如果不是懒加载则批量添加
                    if ($param['lazy'] == '2') {
                        foreach ($members as $member) {
                            $data = $param;
                            $data['member_id'] = $member['id'];
                            $configData[] = $data;
                        }
                    }
                    if ($configData) {
                        $ConfigModel = new ConfigModel;
                        $res1 = $ConfigModel->saveAll($configData);
                    }
                    //var_dump($configData);die;
                } else {
                    //1:设置配置信息
                    $res1 = ConfigModel::create($param);

                }


                $res = $res1 && $res2 && true;
                ConfigModel::checkTrans($res);
            } catch (\Exception $e) {
                ConfigModel::rollbackTrans();
                $res = false;
            }

            if ($res) {
                //xn_add_admin_log('添加权限节点');
                return $this->success('操作成功');
            } else {
                return $this->error('操作失败');
            }
        }
        //得到配置
        //var_dump(bw_config('site_upload2_url',123));die;
        $tab_id = $this->request->get('tab_id');
        //查询所有分类
        $tab = ConfigTab::where('is_show', 1)->select()->toArray();
        //var_dump($tab);die;
        return view('editconfig', ['entity' => null, 'tab' => $tab, 'tab_id' => $tab_id]);
    }


    public function editconfig()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $config = ConfigModel::find($param['id']);
            if (!$config) return $this->error('配置不存在');
            $ConfigTab = ConfigTab::find($param['tab_id']);
            if (!$ConfigTab) return $this->error('配置分类不存在');
            if ($config['scopes'] == 'common') {
                //判断是否存在唯一标识
                $count = ConfigModel::where('config_name', $param['config_name'])->where('dir',$ConfigTab['dir'])->where('id', '<>', $param['id'])->count();
                if ($count) return $this->error('该字段已存在');
            } else {
                //租户不允许变更唯一标识
                if ($param['config_name'] != $config['config_name']) return $this->error('租户配置不能变更配置字段');
                if ($param['tab_id'] != $config['tab_id']) return $this->error('租户配置不能变更配置分类');
            }

            $count = ConfigTab::where('tab_name', $param['config_name'])->count();
            if ($count) return $this->error('该字段分类中已存在');
            //转移富文本
            if ($param['type'] == 'r_textarea') $param['value'] = Util::r_text_decode($param['value']);

            //插入分类标识
            $param['tab_name'] = $ConfigTab['tab_name'];
            $param['scopes'] = $ConfigTab['scopes'];
            $param['dir'] = $ConfigTab['dir'];
            $res = $res1 = $res2 = true;
            ConfigModel::beginTrans();
            try {
                //2:修改租户源数据同时改变租户所有数据
                if ($config['scopes'] == 'member' && $config['member_id'] == 0) {
                    //查询所有租户
                    $memberIds = Member::where('parent_id', 0)->column('id');
                    //查询租户的所有配置
                    $confiIds = ConfigModel::where('config_name', $config['config_name'])->where('member_id', 'in', $memberIds)->column('id');
                    $configData = array();
                    //修改原始数据
                    $entity = $param;
                    $configData[] = $entity;
                    unset($param['id']);
                    foreach ($confiIds as $confiId) {
                        $data = $param;
                        $data['id'] = $confiId;
                        $configData[] = $data;
                    }
                    if ($configData) {
                        $ConfigModel = new ConfigModel;
                        $res1 = $ConfigModel->saveAll($configData);
                    }
                    //var_dump($configData);die;
                } else {
                    //1:设置配置信息
                    $res1 = ConfigModel::update($param);

                }


                $res = $res1 && $res2 && true;
                ConfigModel::checkTrans($res);
            } catch (\Exception $e) {
                ConfigModel::rollbackTrans();
                $res = false;
            }

            if ($res) {
                //xn_add_admin_log('修改管理组名称');
                return $this->success('更新成功');
            } else {
                return $this->error('操作失败');
            }
        }
        $id = $this->request->get('id');
        $tab_id = $this->request->get('tab_id');
        $data = ConfigModel::getEntity($id);
        //$list = ConfigTab::select()->toArray();
        // var_dump($data['parameter']);die;
        //查询所有分类
        $tab = ConfigTab::where('is_show', 1)->select()->toArray();

        return view('editconfig', ['entity' => $data, 'tab' => $tab, 'tab_id' => $tab_id]);
    }


    public function showconfig($tab_name = null, $type = null, $config_ids = null)
    {

        $tab_name = $tab_name ?: ($this->request->get('tab_name') ?: null);//配置分类
        $type = $type ?: ($this->request->get('type') ?: null);//配置类型
        $config_ids = $config_ids ?: ($this->request->get('config_ids') ?: null);//配置id

        $data = ConfigModel::getShowData($tab_name, $type, null, 'common', $config_ids);
        //  var_dump($data);die;
        return view('', ['show' => $data]);
    }

    public function showMemberConfig()
    {
        //var_dump(bw_config('ceshi_yanse'));die;
        $tab_name = $this->request->get('tab_name') ?: null;//配置分类
        $type = $this->request->get('type') ?: null;//配置类型
        $config_ids = $this->request->get('config_ids') ?: null;//配置id

        $data = ConfigModel::getShowData($tab_name, $type, null, 'member', $config_ids);
        //  var_dump($data);die;
        return view('', ['show' => $data]);
    }

    public function setValues()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $res = ConfigModel::setValues($param, null, 'common', true);
            if (!$res) return $this->error(ConfigModel::getError('设置失败'));
            return $this->success('更新成功');
        }

    }

    public function setMemberValues()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $res = ConfigModel::setValues($param, null, 'member', true);
            if (!$res) return $this->error(ConfigModel::getError('设置失败'));
            return $this->success('更新成功');
        }

    }


    public function configindex()
    {
        $tab_name = $this->request->get('tab_name') ?: null;//配置分类
        $type = $this->request->get('type') ?: null;//配置类型
        //查询所有分类
        $tab = ConfigTab::where('is_show', 1)->select()->toArray();
        $miniapp = Miniapp::select()->toArray();
        //  var_dump($data);die;
        return view('', ['type' => $type, 'tab_name' => $tab_name, 'tab' => $tab,'miniapp' => $miniapp]);
    }


    /**
     * 配置分类列表
     *
     * @return \think\Response
     */
    public function getconfiglist()
    {


        //搜索条件
        $map = array();
        $sort = 'a.id desc';
        //页数
        $page = input('page/d');
        //条数
        $limit = input('limit/d');
//        //时间开始
//        $time_start    = input('beginTime/s');
//        //时间结束
//        $time_end    = input('endTime/s');
        //订单状态
        $type = input('type/s');
        $type_system = input('type_system/s');
        //订单号
        $info = input('info/s');
        //直播分类
        $status = input('status/s');

        //直播分类
        $tab_id = input('tab_id/s');
        $scopes = input('scopes/s');

        $tabid = input('tabid/s');
        //手机号
        $config_name = input('config_name/s');
        $member_id = input('member_id/s');
        $nickname = input('nickname/s');
        $dir = input('dir/s');
        if($dir){
            $map[] = ['a.dir', '=', $dir];
        }
        if ($member_id !== '') {
            $map[] = ['a.member_id', '=', $member_id];
        }
        if ($nickname) {
            $map[] = ['m.nickname|m.mobile|m.username', 'like', $nickname . '%'];
        }

        if ($scopes != null) {
            $map[] = ['a.scopes', '=', $scopes];
        }
        if ($type_system != null) {
            $map[] = ['t.type', '=', $type_system];
        }
        //订单状态
        if ($type != null) {
            $map[] = ['t.type', '=', $type];
        }


        if ($status !== '') {
            $map[] = ['a.status', '=', $status];
        }
        if ($config_name) {
            $map[] = ['a.config_name', 'like', $config_name . '%'];
        }

        if ($info) {
            $map[] = ['a.info', 'like', $info . '%'];
        }
        if ($tabid) {
            $ConfigTab = ConfigTab::where('tab_name|id', $tabid)->find();
            if ($ConfigTab) $map[] = ['a.tab_id', '=', $ConfigTab['id']];
        }

        if ($tab_id) {
            $map[] = ['a.tab_id', '=', $tab_id];
        }
//            var_dump($tab_id);die;

//        //时间区间
//        if($time_start!=null){
//            $time_start = strtotime($time_start);
//            $map[] = ['a.add_time','>=',$time_start];
//            if($time_end!=null){
//                $time_end = strtotime($time_end);
//                $map[] = ['a.add_time','<=',$time_end];
//            }
//        }elseif($time_end!=null){
//            $time_end = strtotime($time_end);
//            $map[] = ['a.add_time','<=',$time_end];
//            if($time_start!=null){
//                $time_start = strtotime($time_start);
//                $map[] = ['a.add_time','>=',$time_start];
//            }
//        }

        // $map[] = ['a.is_del','=', 0];

        //门店列表
        $list = ConfigModel::alias('a')
            ->field(['a.*,t.title,t.tab_name,t.type as tabtype,m.nickname,m.mobile,m.avatar,d.title as miniapp_name'])
            ->join('bw_sys_config_tab t', 'a.tab_id = t.id', 'left')
            ->join('bw_member m', 'a.member_id = m.id', 'left')
            ->join('miniapp d', 'a.dir = d.dir', 'left')
            ->where($map)
            ->page($page, $limit)
            ->order($sort)
            ->select()->toArray();

        //echo ConfigModel::getLastSql();die;//打印最后一条
        //查询所有的租户原始配置
        $configNames = ConfigModel::where('member_id', 0)->where('scopes', 'member')->column('id', 'config_name');
        $memberConfigIds = array();
        //组合树
        foreach ($list as $val) {
            $memberConfigIds[] = $val['id'];
        }
        //组合树
        foreach ($list as &$value) {
            $value['pid'] = 0;
            if ($value['member_id'] != 0) {
                //如果是租户配置并且pid在查询出的数据中能找到才附上pid
                if (isset($configNames[$value['config_name']]) && in_array($configNames[$value['config_name']], $memberConfigIds)) $value['pid'] = $configNames[$value['config_name']];
            }
        }
        //var_dump($list);die;
        $list = array_merge(AuthNode::tree($list, 'id', 'id', 'pid'));


        //echo Db::table('contract')->getLastSql();die;//打印最后一条sql
        $count = ConfigModel::alias('a')
            ->join('bw_sys_config_tab t', 'a.tab_id = t.id', 'left')
            ->join('bw_member m', 'a.member_id = m.id', 'left')
            ->join('miniapp d', 'a.dir = d.dir', 'left')
            ->where($map)
            ->count();

        //总数
        //列表数据
        $data = array();
        $data['code'] = 0;
        $data['msg'] = '查询成功';
        $data['count'] = $count;
        $data['data'] = $list;
        return json($data);
    }


    /**
     * 更改开启状态
     *
     * @return \think\Response
     */
    public function setconfigshow()
    {
        //门店id
        $id = input('id/d');
        $sort = input('sort/s', null);
        //门店开启状态
        $data = ConfigModel::find($id);
        if ($sort !== null) {
            $data['sort'] = $sort;
        } else {
            if ($data['status'] === 0) {
                $data['status'] = 1;
            } elseif ($data['status'] === 1) {
                $data['status'] = 0;
            };
        }


        $data->save();
        return 'success';
    }


    /**
     * 删除/批量删除
     *
     * @return \think\Response
     */
    public function configsoftdleting()
    {
        //门店ids
        $ids = input('ids/s');
        $ids_array = explode(',', $ids);
        $list = array();

        $res = $res1 = $res2 = true;
        ConfigModel::beginTrans();
        try {
            foreach ($ids_array as $key) {
                $config = ConfigModel::find($key);
                ConfigModel::destroy($key);
                //2:如果是租户配置，删除所有分配置
                if ($config && $config['scopes'] == 'member' && $config['member_id'] == 0) {
                    //查询所有分配置
                    $configIds = ConfigModel::where('config_name', $config['config_name'])->where('scopes', 'member')->column('id');
                    if ($configIds) ConfigModel::destroy($configIds);
                    //var_dump($configData);die;
                }
            }
            $res = $res1 && $res2 && true;
            ConfigModel::checkTrans($res);
        } catch (\Exception $e) {
            ConfigModel::rollbackTrans();
            $res = false;
        }
        if ($res) {
            //xn_add_admin_log('修改管理组名称');
            return 'success';
        } else {
            return 'error';
        }

    }


}
